package iot.ht.controller.htpage.service;

import iot.core.data.*;
import iot.core.data.entity.HTPage;
import iot.core.data.entity.HTPageAuth;

import iot.core.data.mapper.*;
import iot.core.exception.MyException;
import iot.core.manager.id.HTIDManager;
import iot.core.util.StreamUtil;
import iot.ht.controller.htpage.data.HTPageAuthDto;
import iot.ht.controller.htpage.data.HTPageDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.stream.Collectors;

@Slf4j
@Service
public class HTPageService extends ServiceImpl<HTPageMapper, HTPage> implements IHTPageService {
    @Autowired
    HTDBMapper htdbMapper;
    @Autowired
    HTPageAuthMapper htPageAuthMapper;
    @Autowired
    HTCtlMapper htCtlMapper;
    @Autowired
    HTActionMapper htActionMapper;
    @Override
    public HTPageDto InsertInit(){
        var mm=new HTPageDto();
        mm.setImgUrl("layui-icon-form");
        return mm;
    }
    @Override
    public HTPageAuthDto InsertAuthInit(){
        var mm = new HTPageAuthDto();
        return mm;
    }
    @Override
    public HTPageDto Detail(BaseQto qm){
        var m=getBaseMapper().selectById(qm.getId());
        var mm=new HTPageDto();
        getBaseMapper().entityToDto(m,mm);
        mm.setCrt_UName( htdbMapper.getName("htuser",m.getCrt_UId() ) );
        mm.setEdt_UName( htdbMapper.getName("htuser",m.getEdt_UId() ) );

        var qwPageAuth=htPageAuthMapper.getQueryWrapper();
        qwPageAuth.eq("HTPage_Id",mm.getId() );
        qwPageAuth.orderBy(true,true,"SortNo");
        var ldbauth=htPageAuthMapper.selectList(qwPageAuth);
        for(var mauth:ldbauth){
            var mmauth=new HTPageAuthDto();
            htPageAuthMapper.entityToDto(mauth,mmauth);
            mm.getAuths().add(mmauth);
        }
        return mm;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int Insert(HTPageDto mm){
        var qwold=getBaseMapper().getQueryWrapper();
        qwold.eq("code",mm.getCode());
        var mold=getBaseMapper().selectOne(qwold);
        if(!ObjectUtils.isEmpty(mold)){
            throw new MyException("数据重复");
        }
        var m = new  HTPage();
        getBaseMapper().dtoToEntity(mm,m);
        m.setId(HTIDManager.getInstance().nextLong());
        for(var masrc: mm.getAuths())
        {
            var madst=new HTPageAuth();
            htPageAuthMapper.dtoToEntity(masrc, madst);
            madst.setHTPage_Id(m.getId());
            htPageAuthMapper.insert(madst, true );
        }
        return getBaseMapper().insert(m,true);

    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public   int Update(HTPageDto mm){
        var m=getBaseMapper().selectById(mm.getId());
        if(!m.getCode().equals(mm.getCode())){
            var qwold=getBaseMapper().getQueryWrapper();
            qwold.eq("code",mm.getCode());
            var mold=getBaseMapper().selectOne(qwold);
            if(ObjectUtils.isEmpty(mold)){
                throw new MyException("数据重复");
            }
        }
        getBaseMapper().dtoToEntity(mm,m);

        var qwPageAuth=htPageAuthMapper.getQueryWrapper();
        qwPageAuth.eq("HTPage_Id",mm.getId() );
        qwPageAuth.orderBy(true,true,"SortNo");
        var ldbauth=htPageAuthMapper.selectList(qwPageAuth);
        for(var masrc:mm.getAuths()){
            var madst = StreamUtil.get(ldbauth,a->a.getId().equals(masrc.getId()));

            if (madst == null)
            {
                madst=new HTPageAuth();
                htPageAuthMapper.dtoToEntity(masrc, madst);
                madst.setHTPage_Id(m.getId());
                htPageAuthMapper.insert(madst, true );
            }
            else
            {
                htPageAuthMapper.dtoToEntity(masrc, madst);
                htPageAuthMapper.updateById(madst,true);
            }
        }

        for(var madb : ldbauth)
        {
            var masrc= StreamUtil.get(  mm.getAuths(), a->a.getId().equals( madb.getId()) );
            if (masrc == null)
            {
                htPageAuthMapper.deleteById(madb,true);
            }
        }

        return getBaseMapper().updateById(m);
    }


    @Override

    public PageData<HTPageDto> Page(BasePageDTQto qm){
       var qw=getBaseMapper().getQueryWrapper();
        if(StringUtils.hasText(qm.getDTB() )){
            qw.ge("Edt_DT",qm.getDB() );
        }

        if(StringUtils.hasText(qm.getDTE() )){
            qw.lt("Edt_DT",qm.getDE() );
        }

        if(StringUtils.hasText(qm.getKey() )){
            qw.and(qr->{
               qr.like("Code",qm.getKey() )
                       .or()
                       .like("Name",qm.getKey() );

            });

        }
        var sort=qm.getSort();
        qw.orderBy(true,sort.isIsAsc(),sort.getFiled() );


        var r=new PageData<HTPageDto>();
        var r1=getBaseMapper().page( qw,qm );
        r.setTotal(r1.getTotal());
        var l1=r1.getData().stream().map(a->a.getCrt_UId() ).collect(Collectors.toList());
        var l2=r1.getData().stream().map(a->a.getEdt_UId() ).collect(Collectors.toList());
        l1.addAll(l2);
        var lname=htdbMapper.getNames("htuser",l1);

        var data=new ArrayList<HTPageDto>();
        for(var m:r1.getData()){
            var mm=new HTPageDto();
            getBaseMapper().entityToDto(m,mm);
            mm.setCrt_UName(
                    StreamUtil.getOrDefault(lname,a->a.getId().equals(m.getCrt_UId()), IdNameDto.class).getName()
            );

            mm.setEdt_UName(
                    StreamUtil.getOrDefault(lname,a->a.getId().equals(m.getEdt_UId()), IdNameDto.class).getName()
            );

            data.add(mm);
        }
        r.setData(data);
        return r;
    }

    public HTPageDto InsertInitForCtl(long ctlId){
        var mctl=htCtlMapper.selectById(ctlId);
        var qw=htActionMapper.getQueryWrapper();
        qw.eq("CtlFullName",mctl.getCtlFullName() )
                .eq("AuthType","Auth")
                .orderBy(true,true,"Id");
        var laction=htActionMapper.selectList(qw);

        var ename=mctl.getCtlFullName().substring( mctl.getCtlFullName().lastIndexOf(".")+1 ).toLowerCase();
        if(ename.endsWith("controller")){
            ename=ename.substring(0,ename.length()-10 );
        }
        var mm=new HTPageDto();
        mm.setId(htdbMapper.nextLong() );
        mm.setCode("/" + ename + "/index");
        mm.setImgUrl("layui-icon-form");
        mm.setLX("后台");
        mm.setName(mctl.getName());
        mm.setMemo(mctl.getMemo());
        var SortNo = 10;
        for(var mact:laction){
            var mauth=new HTPageAuthDto();
            mauth.setId(htdbMapper.nextLong() );
            mauth.setCode(mact.getFullUrl());
            mauth.setName(mact.getName());
            mauth.setMemo(mact.getMemo());
            mauth.setSortNo((long) SortNo);
            mauth.setUrls(mact.getFullUrl());
            mm.getAuths().add(mauth);
        }
        return mm;

    }

}
